#include "mysql.h"
#include "getmd5"
int getFileSize(char* filename){
    int fd=open(filename,O_RDWR);
    ERROR_CHECK(fd,-1,"open");

    struct stat st;
    fstat(fd,&st);
    close(fd);
    return st.st_size;
}

int getFileType(char* filename){
    int fd=open(filename,O_RDWR);
    ERROR_CHECK(fd,-1,"open");

    struct stat st;
    fstat(fd,&st);
    if(S_ISREG(st.st_mode)){
        renturn 2;
    }else if(S_ISDIR(st.st_mode)){
        return 1;
    }
    close(fd);
    return 0;
}
int insert_new_file(MYSQL* conn,char* username,char* dirname,char* filename){
    //得到parent_id
    char query1[SQL_MAX]={0};
    sprintf(query1,"select parent_id from virtualfile where filename='%s';",dirname);
    mysql_query(conn,query1);
    MYSQL_RES * result1=mysql_store_result(conn);
    MYSQL_ROW parents=mysql_fetch_row(result1);
    int parentid=atoi(parents[0]);
    
    //得到md5
    char md5[32]={0};
    getmd5(filename,md5);
    
    //得到owner_id
    char query2[SQL_MAX]={0};
    sprintf(query2,"select T.owner_id from\
		(select vf.owner_id,parent_id from user\
		inner join\
		virtualfile as vf\
		on user.username='%s') as T\
		where T.parent_id='%d';",username,parentid));
    mysql_query(conn,query2);
    MYSQL_RES * result2=mysql_store_result(conn);
    MYSQL_ROW owner=mysql_fetch_row(result2);
    int ownerid=atoi(owner[0]);
    
    //得到filesize
    int filesize=getFileSize(filename);
    
    //得到type
    int type=getFileType(filename);

    //有了parent_id,filename,owner_id,md5,filesize,type
    //进行insert into virtualfile 操作
    char query[SQL_MAX]={0};
    sprintf(query,"insert into virtualfile\
                    (parent_id,filename,owner_id,md5,filesize,type)\
                    valuse ('%d','%s','%d','%s','%d','%d')\
                    ;",parentid,filename,ownerid,md5,filesize,type);
    mysql_query(conn,query);
    mysql_close(conn);
}
int main(){
    //下面是个人数据库的信息，please use concrete function except the function of maim.
    ////otherwise,those code have not been tested before.
    MYSQL *conn=NULL;
    char* host="localhost";
    char* user="root";
    char* passwd="123456";
    char* db="yourdb";

    conn=mysql_init(NULL);
    mysql_real_connect(conn,host,user,passwd,db,0,NULL,0);
    insert_new_file(conn,"ppc","dir1","file4");//There need the filename of a actual file which trans successfully.
    return 0;
}
